package cn.yqx.bankshop.goods.controller;


import cn.yqx.bankshop.goods.pojo.*;
import cn.yqx.bankshop.goods.service.FormatService;
import cn.yqx.bankshop.goods.service.GoodsService;
import cn.yqx.bankshop.goods.service.OrderService;
import cn.yqx.bankshop.goods.service.SupplierService;
import cn.yqx.bankshop.result.Result;
import cn.yqx.bankshop.result.ResultCode;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/goods")
@Slf4j
public class GoodsController {

    private final static  int TOTAL_MAP_SIZE = 10 ;
    private final static  String IS_NEW_GOODS_KEY = "isNewGoods" ;
    private final static  String IS_ORDER_KEY = "isOrder" ;
    private final static  String IS_LIMIT_KEY = "isLimit" ;
    private final static  String LIMIT_MAX_KEY =  "limitMaxSize";
    private final static  String SUPPLIER_FULLNAME = "supplierFullname" ;
    private final static  String SUPPLIER_NAME = "supplierName" ;
    private final static  String GOODS_ID_KEY = "goods_id" ;
    private final static  String GOODS_NUM_KEY = "goodsNum" ;
    private final static  String PRODUCT_NAME_KEY = "product_name" ;
    private final static  String GOODLIST_KEY = "goodList" ;
    private final static  Integer GOODLIST_INDEX = 2 ;
    private final static  String GOOD_FORMAT_LIST = "goodFormatList" ;
    private final static  String GOOD_FORMAT_KEY_LIST = "goodFormatKeyList" ;
    private final static  String GOOD_FORMAT_VAL_LIST = "goodFormatValList" ;

    @Autowired
    SupplierService supplierService ;
    @Autowired
    GoodsService goodsService ;
    @Autowired
    OrderService orderService ;
    @Autowired
    FormatService formatService ;

    @RequestMapping(value = "/find_new_goods" ,method = RequestMethod.GET)
    public Object findNewGoodds(){

        Result result ;
        try{
            result = Result.success() ;
            HashMap<String ,Object> map = new HashMap<String,Object>(TOTAL_MAP_SIZE) ;
            map.put(IS_NEW_GOODS_KEY,1) ;
            map.put(IS_LIMIT_KEY,1);
            map.put(IS_ORDER_KEY,1) ;
            map.put(LIMIT_MAX_KEY,4) ;
            List<BuGoods> newGoods = goodsService.selectGoodsList(map) ;
            newGoods.stream().forEach((item)->{
                JSONObject json = supplierService.findSupplierById(item.getSupplierId());
                item.setSupplierName(json.getString(SUPPLIER_FULLNAME));
            });
            result.setData(newGoods);
        }catch (Exception e){
            result = Result.failed(ResultCode.SYSTEM_EXECUTION_ERROR) ;
            log.error("error : {} " ,e );
        }

        return result ;
    }

    @RequestMapping(value = "/find_main_business" , method = RequestMethod.GET)
    public Object findMainBusiness(Long supplierId){
        Result result ;
        try{
            result = Result.success() ;
            List<Map<String,Object>> list = goodsService.findMainBusiness(supplierId) ;
            result.setData(list);
        }catch (Exception e){
            result = Result.failed(ResultCode.SYSTEM_EXECUTION_ERROR) ;
            log.error("error : {} ",e);
        }
        return  result ;
    }

    @RequestMapping(value = "/find_goods_top5" ,method = RequestMethod.GET)
    public Object findGoodsTop5(Long supplierId){
        Result result ;
        try{
            result = Result.success() ;
            List<Map<String,Object>> goodsList = orderService.findGoodsTop5(supplierId) ;
            List<Long> ids = new ArrayList<Long>() ;
            goodsList.stream().forEach((item)->{
                ids.add(Long.parseLong(String.valueOf(item.get(GOODS_ID_KEY)))) ;
            });
            List<BuGoods> goods = goodsService.findGoodsByIds(ids) ;
            result.setData(goods);
        }catch (Exception e){
            result = Result.failed(ResultCode.SYSTEM_EXECUTION_ERROR) ;
            log.error("error : {} ",e);
        }

        return result ;
    }

    @RequestMapping(value = "/find_goodsnum_by_supplier",method = RequestMethod.GET)
    public Object findGoodsNum(Long supplierId){
        Result result ;
        try{
            result = Result.success() ;
            JSONObject json = new JSONObject();
            int goodsNum = goodsService.findGoodsNumBySupplierId(supplierId) ;
            json.put(GOODS_NUM_KEY, goodsNum) ;
            result.setData(json);
        }catch (Exception e){
            result = Result.failed(ResultCode.SYSTEM_EXECUTION_ERROR) ;
            log.error("error : {} ",e);
        }
        return result ;
    }

    @RequestMapping(value = "/statistics_by_category" , method = RequestMethod.GET)
    public Object statisticsByCategory(){
        Result result ;
        try{
            result = Result.success() ;
            List<Map<String,Object>> goodList = orderService.findGoodsBySales();

            List<Map<String,Object>> categoryList = goodsService.statisticsByCategory(goodList) ;
            List<Map<String,Object>> goodsAndCategoryList = goodsService.statisticsGoodsByCategory(goodList) ;

            List<Map<String,Object>> list ;
            for(int index = 0 ;index < categoryList.size() ; index ++){
                Map<String,Object> item = categoryList.get(index) ;
                list = new ArrayList<Map<String, Object>>(GOODLIST_INDEX) ;
                for(Map<String,Object> itemGoods : goodsAndCategoryList){
                    if(item.get(PRODUCT_NAME_KEY).equals(itemGoods.get(PRODUCT_NAME_KEY))){
                        if(list.size() == GOODLIST_INDEX){
                            item.put(GOODLIST_KEY,list) ;
                            break;
                        }else {
                            list.add(itemGoods);
                        }
                    }
                }
            }
            result.setData(categoryList);
        }catch (Exception e){
            result = Result.failed(ResultCode.SYSTEM_EXECUTION_ERROR) ;
            log.error(" error : {} " , e );
        }
        return result ;
    }

    @RequestMapping(value = "/find_recommend_goods" , method = RequestMethod.GET)
    public Object findRecommendGoods(Long userId){
        Result result ;
        try{
            result = Result.success() ;
            List<BuGoods> goodsList =  goodsService.findGoods();
            result.setData(goodsList);
        }catch (Exception e){
            result = Result.failed(ResultCode.SYSTEM_EXECUTION_ERROR) ;
            log.error(" error : {} " , e );
        }
        return result ;
    }

    @RequestMapping(value = "/find_good_by_id" , method = RequestMethod.GET)
    public Object findGoodById(Long goodId){
        Result result ;
        try{
            result = Result.success() ;
            BuGoods good = goodsService.findById(goodId) ;
            result.setData(good);
        }catch (Exception e) {
            result = Result.failed(ResultCode.SYSTEM_EXECUTION_ERROR) ;
            log.error(" error : {} " , e );
        }
        return result ;
    }
    @RequestMapping(value = "/find_by_id" , method = RequestMethod.GET)
    public Object findGoodByIdApi(Long goodId){
        BuGoods good = goodsService.findById(goodId) ;
        return good ;
    }

    @RequestMapping(value = "/find_goodformat_by_id",method = RequestMethod.GET)
    public Object findGoodFormatById(Long goodId) {
        Result result ;
        try{
            result = Result.success() ;
            List<BuGoodsFormat> buGoodFormatList = formatService.getGoodFormateByGoodId(goodId);
            List<BuGoodsFormatKey> buGoodsFormatKeyList = formatService.getBuGoodsFormatKeyByGoodId(goodId);
            List<BuGoodsFormatVal> buGoodsFormatValList = formatService.getBuGoodsFormatVal(goodId) ;
            JSONObject json =new  JSONObject() ;

            json.put(GOOD_FORMAT_LIST,buGoodFormatList) ;
            json.put(GOOD_FORMAT_KEY_LIST,buGoodsFormatKeyList) ;
            json.put(GOOD_FORMAT_VAL_LIST,buGoodsFormatValList) ;
            result.setData(json);
        }catch (Exception e){
            result = Result.failed(ResultCode.SYSTEM_EXECUTION_ERROR) ;
            log.error(" error : {} " , e );
        }

        return result ;
    }

    @RequestMapping(value = "find_detatilpara_by_goodId" , method = RequestMethod.GET)
    public Object findDetatilparaByGoodId(Long goodId){
        Result result ;
        try{

            result = Result.success() ;
            List<BuGoodsDetatilPara> list = goodsService.getGoodDetatilParaList(goodId) ;
            result.setData(list);

        }catch (Exception e){
            result = Result.failed(ResultCode.SYSTEM_EXECUTION_ERROR) ;
            log.error(" error : {} " , e );
        }

        return result ;
    }

    @RequestMapping(value = "find_similar_goods_goodName",method = RequestMethod.GET)
    public Object findSimilarGoodsByGoodName(Long userId,Long goodsId){

        return null ;
    }

    @RequestMapping(value = "update_supplier_name")
    public void updateSupplierName() {

        List<BuGoods> goodsList = goodsService.selectAll() ;
        goodsList.stream().forEach((item)->{
            JSONObject json = supplierService.findSupplierById(item.getSupplierId());
            String supplierFullname = json.getString(SUPPLIER_FULLNAME) ;
            if(StringUtils.isEmpty(supplierFullname)){
                supplierFullname = json.getString(SUPPLIER_NAME) ;
            }
            if(!StringUtils.isEmpty(supplierFullname)){
                goodsService.updateSupplierName(supplierFullname,item.getId());
            }

        });
    }

    

}
